package org.lanyu.springainovel.common.config;

import org.lanyu.springainovel.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security配置�?
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private UserService userService;

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用自定义密码编码器，它内部使用BCrypt但提供了基于用户名的盐值方法
        return new CustomPasswordEncoder();
    }

    @Autowired
    private CustomDaoAuthenticationProvider customDaoAuthenticationProvider;

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        // 获取默认的认证管理器
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        
        // 将自定义认证提供者添加到认证管理器中
        // 注意：这里我们不能直接修改AuthenticationManager，因为它是一个接口
        // 实际上，通过在filterChain中配置.authenticationProvider(customDaoAuthenticationProvider)
        // 已经足够将我们的自定义认证提供者注册到Spring Security中
        
        return authenticationManager;
    }

    /**
     * CORS配置
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;
    
    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 启用CORS
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            // 禁用CSRF（适用于API�?
            .csrf(csrf -> csrf.disable())
            // 设置会话管理策略为无状�?
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 配置异常处理
            .exceptionHandling(exception -> exception
                .accessDeniedHandler(customAccessDeniedHandler)
                .authenticationEntryPoint(customAuthenticationEntryPoint)
            )
            // 配置请求授权规则
            .authorizeHttpRequests(auth -> auth
                // 允许无需认证的接口
                .requestMatchers("/auth/login").permitAll() // 登录接口
                .requestMatchers("/auth/register").permitAll() // 注册接口
                .requestMatchers("/proxy").permitAll() // 代理接口
                .requestMatchers("/sse").permitAll() // SSE接口
                .requestMatchers("/filesystem/read").permitAll() // 读取文件接口
                .requestMatchers("/error").permitAll() // 错误页面
                .requestMatchers("/actuator/**").permitAll() // 监控接口
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() // Swagger文档
                .requestMatchers("/static/**", "/public/**", "/resources/**", "/icon/**","/uploads/**").permitAll() // 静态资源
                .requestMatchers("/articles").permitAll() // 文章接口
                .requestMatchers("/chat/generateStream").permitAll() // 聊天生成流接口（临时解决方案）
                .requestMatchers("/chapter/content/generateStream").permitAll() // 章节正文生成流接口
                .requestMatchers("/novel/outline/generate/stream").permitAll() // 大纲生成
                .requestMatchers("/book-roles/batch-generate-stream").permitAll() // 角色 生成
                .requestMatchers("/common/stream/**").permitAll() // 通用流式生成
                .requestMatchers("/prompt/templates/test-stream").permitAll() // 提示词模板测试流接口
                // WebSocket端点允许无需认证访问
                .requestMatchers("/ws-task/**").permitAll() // 通用任务WebSocket端点
                .requestMatchers("/ws-book-analysis/**").permitAll() // 书籍分析WebSocket端点
                .requestMatchers("/ws-unified/**").permitAll() // 统一任务WebSocket端点
                // 其他所有接口需要认证
                .anyRequest().authenticated()
            )
            // 启用JWT认证过滤器
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
            // 配置认证提供者
            .authenticationProvider(customDaoAuthenticationProvider)
            .userDetailsService(userService)
            .formLogin(form -> form.disable());

        return http.build();
    }
}
